import { defineComponent, ref, onMounted } from "vue";
import { RouterView, useRouter } from "vue-router";
import { useSystemStore, useUserStore } from "@/stores";
import { system, user } from "@/api";
import { getToken, isMobile } from "@/utils";

export default defineComponent({
  name: "InitPage",
  setup(_, { slots }) {
    const router = useRouter();
    const systemStore = useSystemStore();
    const userStore = useUserStore();
    const init = ref(false);

    onMounted(async () => {
      try {
        // 先设置默认配置，避免 API 请求失败导致页面无法显示
        const defaultConfig = {
          "ldap-enabled": "0",
          systemH5Url: "",
          systemLogo: "",
          systemName: "PlayEdu PC",
          systemPcUrl: "",
          resourceUrl: {},
          pcIndexFooterMsg: "",
          playerPoster: "",
          playerIsEnabledBulletSecret: false,
          playerIsDisabledDrag: false,
          playerBulletSecretText: "",
          playerBulletSecretColor: "",
          playerBulletSecretOpacity: "",
        };

        systemStore.saveConfigAction(defaultConfig);

        // 尝试获取系统配置
        try {
          const configRes = await system.config();
          const configData = configRes.data;

          const config = {
            "ldap-enabled": configData["ldap-enabled"],
            systemH5Url: configData["system-h5-url"],
            systemLogo: configData["system-logo"],
            systemName: configData["system-name"],
            systemPcUrl: configData["system-pc-url"],
            resourceUrl: configData["resource_url"],
            pcIndexFooterMsg: configData["system-pc-index-footer-msg"],
            playerPoster: configData["player-poster"],
            playerIsEnabledBulletSecret: configData["player-is-enabled-bullet-secret"] && configData["player-is-enabled-bullet-secret"] === "1" ? true : false,
            playerIsDisabledDrag: configData["player-disabled-drag"] && configData["player-disabled-drag"] === "1" ? true : false,
            playerBulletSecretText: configData["player-bullet-secret-text"],
            playerBulletSecretColor: configData["player-bullet-secret-color"],
            playerBulletSecretOpacity: configData["player-bullet-secret-opacity"],
          };

          systemStore.saveConfigAction(config);

          // 检查是否为移动端
          if (isMobile() && configData["system-h5-url"] !== "") {
            const url = configData["system-h5-url"];
            window.location.href = url;
            return;
          }
        } catch (e) {
          console.error("获取系统配置失败，使用默认配置", e);
        }

        // 如果已登录，获取用户信息
        if (getToken()) {
          try {
            const userRes = await user.detail();
            userStore.loginAction(userRes.data);
          } catch (e) {
            console.error("获取用户信息失败", e);
          }
        }

        init.value = true;
      } catch (e) {
        console.error("系统初始化失败", e);
        init.value = true;
      }
    });

    return () => (
      <>
        {init.value && (
          <div style={{ minHeight: 900 }}>
            <RouterView />
          </div>
        )}
      </>
    );
  },
});
